<template>
  <div class="job-page">
    <TablePage
      ref="tablePageRef"
      title="定时任务"
      :data="displayedRows"
      :columns="tableConfig"
      :loading="loading"
      :show-pagination="true"
      :pagination-config="pagination"
      :form-config="formConfig"
      :default-form-data="defaultFormData"
      :search-config="searchConfig"
      :actions-width="140"
      add-title="新增任务"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @search="handleSearch"
      @reset="handleReset"
      @batch-delete="handleBatchDelete"
      @delete="handleDelete"
      @add="handleAddSubmit"
      @edit="handleEditSubmit"
    >
      <template #actions="{ row }">
        <el-tooltip content="编辑" placement="top">
          <el-button link type="primary" :icon="Edit" @click="editRow(row)" />
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-tooltip content="删除" placement="top">
          <el-button link type="danger" :icon="Delete" @click="handleDelete(row)" />
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-dropdown
          trigger="hover"
          placement="bottom-start"
          @command="(cmd) => handleMoreCommand(cmd, row)"
        >
          <el-button link type="primary" :icon="MoreFilled" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-if="row.status === 'RUNNING'" command="pause" :icon="VideoPause"
                >暂停</el-dropdown-item
              >
              <el-dropdown-item v-else command="resume" :icon="VideoPlay">恢复</el-dropdown-item>
              <el-dropdown-item divided command="run" :icon="RefreshRight"
                >执行一次</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <template #batchActions="{ rows, clear }">
        <el-button type="danger" link :icon="Delete" @click="handleBatchDelete(rows)"
          >批量删除</el-button
        >
        <el-divider direction="vertical" />
        <el-button link :icon="Close" @click="clear">清空</el-button>
      </template>
    </TablePage>
  </div>
</template>
<script setup>
import { computed, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit,
  Delete,
  Close,
  VideoPause,
  VideoPlay,
  RefreshRight,
  MoreFilled,
} from '@element-plus/icons-vue'
import TablePage from '@/components/TablePage/index.vue'
import { jobApi } from '@/api/job'
import { searchConfig, tableConfig } from './config/pageConfig'
import { formConfig, getDefaultFormData } from './config/formConfig'

// 加载状态
const loading = ref(false)

// 数据
const allRows = ref([])

// 搜索与分页
const searchState = ref({ keyword: '', group: '', status: '' })

const pagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50],
})

const filteredRows = computed(() => {
  const { keyword, group, status } = searchState.value
  return allRows.value.filter((r) => {
    const matchKeyword =
      !keyword ||
      [r.name, r.classPath].some((t) => String(t).toLowerCase().includes(keyword.toLowerCase()))
    const matchGroup = !group || r.group === group
    const matchStatus = !status || r.status === status
    return matchKeyword && matchGroup && matchStatus
  })
})

const displayedRows = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredRows.value.slice(start, end)
})

// 时间格式化
const formatTime = (val) => {
  if (!val) return '—'
  try {
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return '—'
    const pad = (n) => String(n).padStart(2, '0')
    const y = d.getFullYear()
    const m = pad(d.getMonth() + 1)
    const day = pad(d.getDate())
    const hh = pad(d.getHours())
    const mm = pad(d.getMinutes())
    const ss = pad(d.getSeconds())
    return `${y}-${m}-${day} ${hh}:${mm}:${ss}`
  } catch {
    return '—'
  }
}

// 后端数据转换（与后端字段保持一致）
const transformJob = (item) => {
  const name = item.jobName || ''
  const group = item.jobGroup || ''
  const classPath = item.jobClass || ''
  const cron = item.cronExpression || ''
  // 将后端 triggerState 转换为前端使用的 RUNNING/PAUSED
  const triggerState = (item.triggerState || '').toUpperCase()
  const status = triggerState.startsWith('PAUSED') ? 'PAUSED' : 'RUNNING'
  const lastRunAt = formatTime(item.previousFireTime)
  const nextRunAt = formatTime(item.nextFireTime)
  const description = item.description || ''
  return {
    id: `${name}@@${group}`,
    name,
    group,
    classPath,
    cron,
    status,
    description,
    jobData: item.jobDataMap || {},
    lastRunAt,
    nextRunAt,
  }
}

// 加载列表
const loadList = async () => {
  loading.value = true
  try {
    const list = await jobApi.list()
    allRows.value = Array.isArray(list) ? list.map(transformJob) : []
    pagination.value.total = filteredRows.value.length
  } catch (e) {
    allRows.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadList()
})

const defaultFormData = getDefaultFormData()

// 打开新增/编辑
const tablePageRef = ref(null)
const editRow = (row) => {
  tablePageRef.value?.handleEdit?.(row)
}
const handleMoreCommand = (cmd, row) => {
  if (cmd === 'pause') return pauseJob(row)
  if (cmd === 'resume') return resumeJob(row)
  if (cmd === 'run') return runOnce(row)
}

// 监听搜索与分页
const handleSearch = (params) => {
  searchState.value = { ...searchState.value, ...params }
  pagination.value.currentPage = 1
  loadList()
}
const handleReset = () => {
  searchState.value = { keyword: '', group: '', status: '' }
  pagination.value.currentPage = 1
  loadList()
}
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  loadList()
}
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  loadList()
}

// 表单提交（新增/编辑）
const handleAddSubmit = async (data) => {
  try {
    await jobApi.create({
      jobName: data.name,
      jobGroup: data.group,
      jobCron: data.cron,
      jobClass: data.classPath,
      description: data.description,
      jobData: data.jobData || {},
    })
    ElMessage.success('新增成功')
    await loadList()
  } catch (e) {
    console.error('新增失败:', e)
  }
}
const handleEditSubmit = async (data) => {
  try {
    await jobApi.update(data.name, data.group, {
      newCronExpression: data.cron,
      description: data.description,
      jobData: data.jobData || {},
    })
    ElMessage.success('修改成功')
    await loadList()
  } catch (e) {
    console.error('编辑失败:', e)
  }
}

// 删除
const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确认删除任务「${row.name}」吗？`, '提示', { type: 'warning' })
  try {
    await jobApi.delete(row.name, row.group)
    ElMessage.success('删除成功')
    await loadList()
  } catch (e) {}
}
const handleBatchDelete = async (rows) => {
  if (!rows?.length) return
  await ElMessageBox.confirm(`确认删除选中 ${rows.length} 个任务吗？`, '提示', { type: 'warning' })
  try {
    await Promise.all(rows.map((r) => jobApi.delete(r.name, r.group)))
    ElMessage.success('批量删除成功')
    await loadList()
  } catch (e) {}
}

// 暂停/恢复/执行一次
const pauseJob = async (row) => {
  try {
    await jobApi.pause(row.name, row.group)
    ElMessage.success('已暂停')
    await loadList()
  } catch (e) {}
}
const resumeJob = async (row) => {
  try {
    await jobApi.resume(row.name, row.group)
    ElMessage.success('已恢复')
    await loadList()
  } catch (e) {}
}
const runOnce = async (row) => {
  try {
    await jobApi.trigger(row.name, row.group)
    ElMessage.success(`已触发「${row.name}」执行一次`)
    await loadList()
  } catch (e) {}
}
</script>

<style lang="scss" scoped>
.job-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.table-page) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.table-page .el-card:last-child) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.table-page .el-card:last-child .el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  min-height: 0;
}

:deep(.table-page .table-content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.table-page .el-table) {
  flex: 1;
  min-height: 0;
}

:deep(.table-page .el-table__body-wrapper) {
  max-height: none;
  overflow-y: auto;
}

:deep(.table-page .el-pagination) {
  flex-shrink: 0;
}

// 移动端抽屉优化
@media screen and (max-width: 768px) {
  // 抽屉样式优化
  :deep(.el-drawer__wrapper) {
    .el-drawer {
      width: 100vw !important;
      height: 100vh !important;
      border-radius: 0;
      display: flex !important;
      flex-direction: column !important;
    }

    .el-drawer__body {
      flex: 1 !important;
      overflow: hidden !important;
      display: flex !important;
      flex-direction: column !important;
      padding: 0 !important;
    }
  }

  // 表单样式优化
  :deep(.drawer-form) {
    .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        font-size: 14px;
        padding-bottom: 8px;
        display: block;
        width: 100%;
      }

      .el-form-item__content {
        margin-left: 0 !important;

        // 输入框优化
        .el-input {
          .el-input__wrapper {
            min-height: 44px;
            border-radius: 8px;
            font-size: 16px; // 防止iOS缩放
          }

          .el-input__inner {
            font-size: 16px;
          }
        }

        // 文本域优化
        .el-textarea {
          .el-textarea__inner {
            min-height: 88px;
            border-radius: 8px;
            font-size: 16px;
            line-height: 1.5;
            padding: 12px;
          }
        }

        // Cron表达式组件优化
        .cron-preview {
          .cron-buttons-desktop {
            display: none !important;
          }

          .cron-buttons-mobile {
            display: flex !important;
          }

          .cron-buttons-mobile .el-button {
            height: 44px !important;
            font-size: 15px !important;
            padding: 12px !important;
            border-radius: 8px !important;
            flex: 1 !important;
            min-width: 0 !important;
          }

          // 预设面板移动端适配
          .cron-presets {
            position: fixed !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            width: calc(100vw - 32px) !important;
            max-width: 400px !important;
            z-index: 10001 !important;
            margin: 0 !important;

            > div {
              max-height: 50vh !important;
              overflow-y: auto !important;
              padding: 16px !important;
              border-radius: 12px !important;
              background: white !important;
              box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15) !important;

              &:last-child {
                display: grid !important;
                grid-template-columns: 1fr !important;
                gap: 8px !important;

                > div {
                  padding: 12px !important;
                  border-radius: 8px !important;
                  border: 1px solid #e0e0e0 !important;

                  &:active {
                    transform: scale(0.98) !important;
                    background-color: #f0f9ff !important;
                  }
                }
              }
            }
          }
        }

        // 任务参数编辑器优化
        .job-data-editor {
          .el-button {
            min-width: auto;
            padding: 10px 16px;
            font-size: 14px;
            border-radius: 6px;

            &[type='text'] {
              padding: 6px;
            }
          }

          // 弹窗移动端优化
          .job-data-editor-modal {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100vh - 60px) !important;
            max-height: calc(100vh - 60px) !important;
            padding: 16px !important;
            border-radius: 12px !important;
            display: flex !important;
            flex-direction: column !important;
            box-sizing: border-box !important;

            > div:first-child {
              margin-bottom: 16px !important;
              padding-bottom: 12px !important;
              flex-shrink: 0 !important;

              h3 {
                font-size: 18px !important;
              }
            }

            div:nth-child(2) {
              flex: 1 !important;
              margin-bottom: 16px !important;
              min-height: 0 !important;
              display: flex !important;

              textarea {
                flex: 1 !important;
                font-size: 16px !important;
                padding: 12px !important;
                border-radius: 8px !important;
                resize: none !important;
                border: 1px solid #e0e0e0 !important;
                outline: none !important;
                box-sizing: border-box !important;

                &:focus {
                  border-color: #409eff !important;
                  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
                }
              }
            }

            .mobile-button-container {
              flex-shrink: 0 !important;
              background: white !important;

              .el-button {
                height: 44px !important;
                font-size: 15px !important;
                border-radius: 8px !important;
                flex: 1 !important;
                min-width: 0 !important;
              }
            }
          }
        }
      }
    }
  }

  // 抽屉底部按钮优化
  :deep(.drawer-footer) {
    padding: 16px;
    background: white;
    border-top: 1px solid var(--el-border-color-light);
    display: flex;
    justify-content: space-between;
    gap: 12px;
    position: sticky !important;
    bottom: 0 !important;
    z-index: 10 !important;

    .el-button {
      flex: 1;
      min-width: auto;
      height: 44px;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;

      &[type='default'] {
        border: 1px solid var(--el-border-color);
        background: white;
        color: var(--el-text-color-primary);

        &:active {
          background: var(--el-fill-color-light);
        }
      }

      &[type='primary'] {
        background: var(--el-color-primary);
        border: none;

        &:active {
          background: var(--el-color-primary-dark-2);
        }
      }
    }
  }

  // 抽屉标题优化
  :deep(.el-drawer__header) {
    padding: 16px 20px 12px;
    border-bottom: 1px solid var(--el-border-color-light);

    .el-drawer__title {
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .el-drawer__close-btn {
      width: 32px;
      height: 32px;
      border-radius: 6px;

      &:hover {
        background: var(--el-fill-color-light);
      }

      &:active {
        background: var(--el-fill-color);
      }
    }
  }

  // 抽屉内容区域优化
  :deep(.drawer-scrollbar) {
    height: calc(100vh - 124px) !important;
    padding: 0 16px;
    overflow-y: auto !important;
    max-height: calc(100vh - 124px) !important;

    .form-content {
      padding: 20px 0 120px; // 底部留够空间显示按钮和滚动
      min-height: calc(100vh - 244px); // 确保内容有足够高度
    }
  }
}

// 超小屏优化（iPhone SE等）
@media screen and (max-width: 375px) {
  :deep(.drawer-form) {
    .el-form-item {
      margin-bottom: 16px;

      .el-form-item__content {
        .cron-preview {
          .cron-presets {
            width: calc(100vw - 16px);

            > div:last-child {
              max-height: 40vh;
            }
          }
        }
      }
    }
  }

  :deep(.drawer-scrollbar) {
    padding: 0 12px;
    overflow-y: auto !important;

    .form-content {
      padding: 16px 0 120px; // 底部留够空间
      min-height: calc(100vh - 244px);
    }
  }

  :deep(.drawer-footer) {
    padding: 12px;

    .el-button {
      height: 40px;
      font-size: 15px;
    }
  }
}

// 横屏优化
@media screen and (max-width: 768px) and (orientation: landscape) {
  :deep(.drawer-scrollbar) {
    height: calc(100vh - 100px) !important;
    overflow-y: auto !important;
    max-height: calc(100vh - 100px) !important;
  }

  :deep(.drawer-form) {
    .el-form-item {
      margin-bottom: 16px;
    }
  }

  :deep(.drawer-footer) {
    position: sticky !important;
    bottom: 0 !important;
    background: white !important;
    z-index: 10 !important;
  }
}
</style>
